package ren.yugong.fileutil;

import java.io.*;

public class TxtTemplateSplitWriteStream<T> implements TxtWriteStream<T> {

    private TxtTemplateModel<T> templateModel;
    private BufferedWriter writer;

    protected TxtTemplateSplitWriteStream(TxtTemplateModel<T> templateModel) {
        this.templateModel = templateModel;
    }

    @Override
    public void open(File file) {
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), templateModel.getCharset()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void write(T t) {
        String line = TxtLineObject.line(t);
        try {
            writer.write(line + templateModel.getLineSeparator());
        } catch (IOException e) {
            throw new TemplateCommonException(e);
        }
    }

    @Override
    public void close() {
        if (null != writer) {
            try {
                writer.close();
            } catch (IOException e) {
                throw new TemplateCommonException(e);
            }
        }
    }
}
